<template>
  <div class="app-container">
    <template>
      <div class="hidden-md-and-up">
        <el-alert title="如若不适应手机端操作，建议使用电脑操作" type="warning" />
      </div>
    </template>
    <div class="table-container">
      <div style="padding-bottom:20px; display: flex;">
        <div style="width: 260px;">
          <label>平台名称</label>
          <el-input v-model="search.platformName" size="medium" placeholder="输入平台名称" style="width: 160px;" />
        </div>
        <div style="width: 260px;">
          <label>级别</label>
          <el-input v-model="search.level" size="medium" placeholder="输入级别" style="width: 160px;" />
        </div>
        <div style="width: 600px; display: flex; align-items: center; gap: 8px">
          <label>批准时间</label>
          <div style="flex: 1">
            <el-date-picker
              v-model="search.approvalTime.DateBegin"
              type="datetime"
              placeholder="起始时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            />
          </div>
          <span style="flex-shrink: 0; margin: 0 4px">-</span>
          <div style="flex: 1">
            <el-date-picker
              v-model="search.approvalTime.DateEnd"
              type="datetime"
              placeholder="结束时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            />
          </div>
        </div>
      </div>
      <div style="padding-bottom:20px; display: flex;">
        <div style="width: 260px;">
          <label>依托学院</label>
          <el-input v-model="search.supportCollege" size="medium" placeholder="输入依托学院" style="width: 160px;" />
        </div>
        <div style="width: 260px;">
          <label>负责人/联系人</label>
          <el-input v-model="search.contactPerson" size="medium" placeholder="输入负责人/联系人" style="width: 160px;" />
        </div>
        <div style="width: 260px;">
          <label>平台类别</label>
          <el-cascader
            v-model="search.platformCategory"
            :options="nationalEconomy_options"
            :props="{ expandTrigger: 'hover' }"
            filterable
            clearable
            :show-all-levels="true"
            style="width: 160px;"
            @change="handlePlatformCategoryChange"
            @focus="fetchPlatformCategories"
          />
        </div>
        <div style="width: 260px;">
          <label>运营状态</label>
          <el-select v-model="search.operationStatus" size="medium" placeholder="请选择" style="width: 160px;">
            <el-option label="全部" value="" />
            <el-option label="运营中" value="运营中" />
            <el-option label="终止运营" value="终止运营" />
          </el-select>
        </div>
      </div>
      <div style="padding-bottom:20px; display: flex;">
        <div style="width: 220px;">
          <label>审核状态</label>
          <el-select v-model="status" size="medium" placeholder="请选择" style="width: 160px;" @change="statusChange">
            <el-option label="全部" value="" />
            <el-option label="草稿" value="草稿" />
            <el-option label="待院审核" value="待院审核" />
            <el-option label="被院级退回" value="被院级退回" />
            <el-option label="待校审核" value="待校审核" />
            <el-option label="被校级退回" value="被校级退回" />
            <el-option label="审核通过" value="审核通过" />
          </el-select>
        </div>
        <div style="margin-left: 20px;" />
        <el-button type="success" size="medium" plain icon="el-icon-download" @click="excel_dialog = true">导出</el-button>
      </div>
      <el-table
        v-loading="paperListLoading"
        :data="paperList"
        element-loading-text="Loading"
        border
        fit
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ (p1_page - 1) * p1_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="平台名称" min-width="180" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.platformName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="平台类别" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.platformCategoryName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="级别" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.level }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批准单位" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.approvalUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="依托学院" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.supportCollege }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批准时间" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.approvalTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人/联系人" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.contactPerson }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="运营状态"
          :filters="[{ text: '运营中', value: '运营中' }, { text: '终止运营', value: '终止运营' }]"
          :filter-method="filterTag"
          filter-placement="bottom-end"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.operationStatus === '运营中' ? 'success' : 'info'">{{ scope.row.operationStatus || '运营中' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="审核状态"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag>
            <el-tag v-if="scope.row.status === '被院级退回' || scope.row.status === '被校级退回'" type="warning">{{ scope.row.reason }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="230">
          <template slot-scope="scope">
            <el-popover
              :ref="`popoverpass-${scope.$index}`"
              placement="top"
              width="160"
            >
              <p>确认通过吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="scope._self.$refs[`popoverpass-${scope.$index}`].doClose()">取消</el-button>
                <el-button type="primary" size="mini" @click="thesis_pass(scope.$index, scope.row)">确定</el-button>
              </div>
            </el-popover>
            <el-button
              size="mini"
              @click="open_infoview_dialog(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="thesis_back(scope.row)"
            >
              退回
            </el-button>
            <el-button
              v-popover="`popoverpass-${scope.$index}`"
              size="mini"
              type="success"
            >
              通过
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :current-page="p1_page"
          :page-sizes="[1,2,3,10, 20, 30, 40]"
          :page-size="p1_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="p1_total"
          @size-change="p1_sizechange"
          @current-change="p1_currentchange"
        />
        <!-- @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
        <!-- 使用了size-change和current-change事件来处理页码大小和当前页变动时候触发的事件。 -->
      </div>
      <!-- 导出对话框 -->
      <el-dialog title="导出excel" :visible.sync="excel_dialog" width="60%">
        <el-alert
          title="请选择需要导出的数据"
          type="success"
          description="选择的数据为表头，未选择的数据将不会导出"
          :closable="false"
        />
        <div style="margin: 15px;">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="check_fields" @change="handleCheckedFieldsChange">
            <el-checkbox v-for="field in fields_list" :key="field" :label="field">{{ field }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <el-alert
          title="请选择时间范围"
          type="success"
          description="选择导出数据的时间范围"
          :closable="false"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="excel_dialog = false">关 闭</el-button>
          <download-excel
            style="display:inline-block !important;margin-left:10px;"
            :data="EXCEL.DetailsForm"
            :fields="EXCEL.json_fields"
            :header="EXCEL.title"
            type="xls"
            name="科研平台数据导出.xls"
            :fetch="createExportData"
            :before-generate="startDownload"
            :before-finish="finishDownload"
          >
            <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
            <el-button type="success" plain>确认导出</el-button>
          </download-excel>
        </div>
      </el-dialog>
      <el-dialog title="编辑信息" :visible.sync="infoview_dialog" width="75%">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <div class="el-descriptions__title">科研平台信息</div>
            </template>
            <el-dialog title="科研平台信息" :visible.sync="thesis_info_dialog" width="60%" append-to-body :close-on-click-modal="false">
              <el-form :model="thesis_add_form2" label-position="top" label-width="160px" autocomplete="off">
                <el-row>
                  <el-col :xs="20" :sm="20" :md="10" :lg="10" :xl="8">
                    <el-form-item label="平台名称" prop="platformName">
                      <el-input v-model="thesis_add_form2.platformName" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="1" :sm="1" :md="2" :lg="2" :xl="2">
                    <br>
                  </el-col>
                  <el-col :xs="20" :sm="20" :md="10" :lg="10" :xl="8">
                    <el-form-item label="平台类别" prop="platformCategory">
                      <el-cascader
                        v-model="thesis_add_form2.platformCategory"
                        :options="nationalEconomy_options"
                        :props="{ expandTrigger: 'hover' }"
                        filterable
                        clearable
                        :show-all-levels="true"
                        style="width: 100%;"
                        class="cascader"
                        @change="handleEditFormPlatformCategoryChange"
                        @focus="fetchPlatformCategories"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :xs="20" :sm="20" :md="10" :lg="10" :xl="8">
                    <el-form-item label="级别" prop="level">
                      <el-select v-model="thesis_add_form2.level" placeholder="请选择">
                        <el-option label="国家级" value="国家级" />
                        <el-option label="省部级" value="省部级" />
                        <el-option label="市/校级" value="市/校级" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="1" :sm="1" :md="2" :lg="2" :xl="2">
                    <br>
                  </el-col>
                  <el-col :xs="20" :sm="20" :md="10" :lg="10" :xl="8">
                    <el-form-item label="批准单位" prop="approvalUnit">
                      <el-input v-model="thesis_add_form2.approvalUnit" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :xs="20" :sm="20" :md="20" :lg="10" :xl="8">
                    <el-form-item label="批准时间" prop="approvalTime">
                      <el-date-picker
                        v-model="thesis_add_form2.approvalTime"
                        type="datetime"
                        placeholder="选择日期时间"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="1" :sm="1" :md="2" :lg="2" :xl="2">
                    <br>
                  </el-col>
                  <el-col :xs="20" :sm="20" :md="20" :lg="10" :xl="8">
                    <el-form-item label="依托学院" prop="supportCollege">
                      <el-select
                        v-model="thesis_add_form2.supportCollege"
                        :loading="deptLoading"
                        placeholder="请选择依托学院"
                        filterable
                        clearable
                        @focus="fetchDeptData"
                        @change="handleSupportCollegeChange2"
                      >
                        <el-option v-for="item in dept_options" :key="item.deptID" :label="item.deptName" :value="item.deptName" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :xs="20" :sm="20" :md="10" :lg="10" :xl="8">
                    <el-form-item label="项目负责人工号" prop="contactPersonId">
                      <el-autocomplete
                        v-model="thesis_add_form2.contactPersonId"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入工号搜索"
                        :trigger-on-focus="false"
                        @select="authorIdHandleSelect"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="1" :sm="1" :md="2" :lg="2" :xl="2">
                    <br>
                  </el-col>
                  <el-col :xs="20" :sm="20" :md="10" :lg="10" :xl="8">
                    <el-form-item label="项目负责人" prop="contactPerson">
                      <el-input
                        v-model="thesis_add_form2.contactPerson"
                        placeholder="仅支持通过工号搜索填充"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="1" :sm="1" :md="2" :lg="2" :xl="2">
                    <br>
                  </el-col>
                  <el-col :xs="20" :sm="20" :md="10" :lg="10" :xl="8">
                    <el-form-item label="运营状态" prop="operationStatus">
                      <el-select v-model="thesis_add_form2.operationStatus" placeholder="请选择">
                        <el-option label="运营中" value="运营中" />
                        <el-option label="终止运营" value="终止运营" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-popover
                  ref="dialog2"
                  v-model="visible2"
                  placement="top"
                  width="160"
                >
                  <p>关闭后，已填写的内容会丢失，建议保存为草稿，确定要关闭吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="visible2 = false">取消</el-button>
                    <el-button type="primary" size="mini" @click="visible2 = false;thesis_info_dialog = false;">确定</el-button>
                  </div>
                </el-popover>
                <el-button v-popover:dialog2>关 闭</el-button>
                <el-button type="primary" @click="save_add_form2(thesis_add_form2)">保 存</el-button>
              </div>
            </el-dialog>

            <el-descriptions :column="2" size="medium" border :label-style="{width:'25%'}" :content-style="{width:'25%'}">
              <el-descriptions-item label="平台名称">
                {{ infoview1.platformName }}
              </el-descriptions-item>
              <el-descriptions-item label="平台类别">
                {{ infoview1.platformCategoryName }}
              </el-descriptions-item>
              <el-descriptions-item label="级别">
                {{ infoview1.level }}
              </el-descriptions-item>
              <el-descriptions-item label="批准单位">
                {{ infoview1.approvalUnit }}
              </el-descriptions-item>
              <el-descriptions-item label="批准时间">
                {{ infoview1.approvalTime }}
              </el-descriptions-item>
              <el-descriptions-item label="依托学院">
                {{ infoview1.supportCollege }}
              </el-descriptions-item>
              <el-descriptions-item label="项目负责人工号">
                {{ infoview1.contactPersonId }}
              </el-descriptions-item>
              <el-descriptions-item label="项目负责人">
                {{ infoview1.contactPerson }}
              </el-descriptions-item>
              <el-descriptions-item label="退回原因">
                {{ infoview1.reason }}
              </el-descriptions-item>
              <el-descriptions-item label="运营状态">
                <el-tag :type="infoview1.operationStatus === '运营中' ? 'success' : 'info'">{{ infoview1.operationStatus || '运营中' }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <div class="el-descriptions__title">附件信息</div>
            </template>
            <div style="margin-bottom: 10px;">
              <span>平台简介参考附件1.1：</span>
              <el-link type="primary" :href="$FILE_PATH+'/file/附件/附件1.1.pdf'" target="_blank">附件1.1</el-link>
            </div>
            <div class="upload">
              <div class="uploadBox">
                <el-upload
                  ref="upload"
                  class="upload-demo"
                  drag
                  :action="$BACK_PATH+'/fileUpload/uploadfileTplatform'"
                  accept=".jpg,.png,.doc,.docx,.xls,.xlsx,.pdf"
                  :on-success="handleFileSuccess"
                  :show-file-list="true"
                  :headers="{ 'X-Token': $store.getters.token }"
                  multiple
                  :disabled="infoview1.status === '待院审核' || infoview1.status === '待校审核' || infoview1.status === '审核通过'"
                  :before-upload="beforeFileUpload"
                  @click.native="handleUploadClick"
                >
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png/doc/xls/pdf/docx/xlsx文件，且不超过50MB</div>
                </el-upload>
              </div>
              <div class="uploadText">
                <el-alert
                  title="注意事项"
                  type="warning"
                  :closable="false"
                  :show-icon="true"
                >
                  <p>1、一次上传一个文件，上传完成的文件会在下方表格中显示</p>
                  <p>2、在下方表格中您可以进行下载和删除操作</p>
                  <p>3、本模块您需要上传的附件有"XXXXX"、"XXXXXX"</p>
                  <p>4、还需要提交平台获批相应批文、平台简介（平台简介参考附件1.1）</p>
                </el-alert>
              </div>
            </div>
            <el-table
              v-loading="fileListLoading"
              :data="fileList"
              element-loading-text="Loading"
              border
              fit
            >
              <el-table-column type="index" align="center" width="55" />
              <el-table-column align="left" label="文件名称" min-width="150">
                <template slot-scope="scope">
                  {{ scope.row.filename }}
                </template>
              </el-table-column>
              <el-table-column align="left" label="文件大小" min-width="150">
                <template slot-scope="scope">
                  <span v-if="scope.row.filesize / 1024 / 1024 < 1">{{ (scope.row.filesize / 1024).toFixed(2) + 'KB' }}</span>
                  <span v-else>{{ (scope.row.filesize / 1024 / 1024).toFixed(2) + 'MB' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="left" label="上传时间" min-width="150">
                <template slot-scope="scope">
                  {{ scope.row.filedate }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="150">
                <template slot-scope="scope">
                  <el-popover
                    :ref="`popoverdelete-${scope.$index}`"
                    placement="top"
                    width="160"
                  >
                    <p>确认删除本行吗？该操作不可撤销</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="scope._self.$refs[`popoverdelete-${scope.$index}`].doClose()">取消</el-button>
                      <el-button type="primary" size="mini" @click="deleteFile(scope.$index, scope.row)">确定</el-button>
                    </div>
                  </el-popover>
                  <el-button
                    size="mini"
                    @click="downloadFile(scope.row)"
                  >
                    下载
                  </el-button>
                  <el-button
                    v-popover="`popoverdelete-${scope.$index}`"
                    size="mini"
                    type="danger"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template slot="title">
              <div class="el-descriptions__title">审核记录</div>
            </template>
            <el-table
              v-loading="platformAuditListLoading"
              :data="platformAuditList"
              element-loading-text="Loading"
              border
              fit
            >
              <el-table-column type="index" align="center" label="序号" width="55" />
              <el-table-column align="center" label="审核员职位" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.auditerRole }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="审核员姓名" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.auditerName }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="项目状态变化" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.statusChange }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="审核意见" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.auditOpinion }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="审核时间" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.auditerTime }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
        <div slot="footer" class="dialog-footer">
          <el-button @click="infoview_dialog = false">关 闭</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getMyPaperList, platform_back_xiaoji, platform_pass_xiaoji, platform_add_file, platform_page_file, platform_delete_file, getUserPlatforms, platform_add, platform_update, platform_delete, platform_commit, thesis_withdraw, getPlatformCategories } from '@/api/platform'
import { getDepts } from '@/api/system'
import { Message, Loading } from 'element-ui'
import { mapGetters } from 'vuex'
import { get_thesis_Audit } from '@/api/audit'
import { getUserByAccount } from '@/api/user'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        运营中: 'success',
        终止运营: 'info',
        草稿: 'info',
        待院审核: 'warning',
        被院级退回: 'danger',
        待校审核: 'warning',
        被校级退回: 'danger',
        审核通过: 'success'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      timeout: null,
      loadingInstance: null, // 导出时的加载实例
      platformCategoryOptions: [], // 平台类别选项
      dept_options: [], // 学院选项
      deptLoading: false, // 学院数据加载状态
      deptMap: {}, // 部门名称到ID的映射
      nationalEconomy_options: [], // 国民经济分类选项
      sourceCascaderLoading: null, // 级联选择器加载状态
      search: {
        platformName: '',
        platformCategory: [], // 平台类别数组，与申报保持一致
        platformCategoryName: '', // 平台类别名称，默认为空字符串
        level: '',
        approvalTime: {
          DateBegin: '',
          DateEnd: ''
        },
        supportCollege: '',
        supportCollegeid: '', // 依托学院ID
        contactPerson: '',
        operationStatus: '',
        status: ''
      },
      status: '',

      thesis_info_dialog: false,
      infoview_dialog: false,
      excel_dialog: false,

      visible2: false,
      all_fields: {
        '平台名称': 'platformName',
        '平台类别': 'platformCategoryName',
        '级别': 'level',
        '批准单位': 'approvalUnit',
        '批准时间': 'approvalTime',
        '依托学院': 'supportCollege',
        '项目负责人工号': 'contactPersonId',
        '项目负责人': 'contactPerson',
        '运营状态': 'operationStatus',
        '录入人': 'entered',
        '录入日期': 'EnteredTime',
        '审核状态': 'status',
        '未通过原因': 'reason',
        '平台ID': 'id'
      },
      fields_list: [
        '平台名称',
        '平台类别',
        '级别',
        '批准单位',
        '批准时间',
        '依托学院',
        '项目负责人工号',
        '项目负责人',
        '运营状态',
        '录入人',
        '录入日期',
        '审核状态',
        '未通过原因',
        '平台ID'
      ],
      check_fields: [],
      checkAll: false,
      isIndeterminate: false,
      EXCEL: {
        title: '科研平台数据',
        json_fields: null,
        DetailsForm: null
      },
      thesis_add_form2: {
        enteredName: '',
        entered: '',
        platformCategory: [], // 平台类别数组，与申报保持一致
        platformCategoryName: '', // 平台类别名称，默认为空字符串
        level: '',
        approvalUnit: '',
        supportCollege: '',
        supportCollegeid: '', // 依托学院ID
        contactPersonId: '', // 负责人工号
        contactPerson: '',
        operationStatus: '运营中',
        approvalTime: '',
        enteredtime: '',
        status: '',
        reason: ''
      },
      // 用于跟踪按钮状态的对象
      committedButtons: {},
      paperList: [],
      paperListLoading: false,
      p1_size: 10,
      p1_total: 0,
      p1_page: 1,
      back_post: {
        id: '',
        reason: ''
      },
      infoview1: {
        address: '',
        id: '',
        workID: '',
        workcate: '',
        workmethod: '',
        workname: '',
        workorigin: '',
        level: '',
        platformName: '',
        annex: '',
        approvalUnit: '',
        approvalTime: '',
        bookChinese: '',
        bookForeign: '',
        classifi: '',
        compositionMethod: '',
        compositionType: '',
        cooperateUnit: '',
        operationStatus: '运营中',
        count: '',
        devicesFee: '',
        disciplineClassifi: '',
        doctor: '',
        email: '',
        Entered: '',
        EnteredTime: '',
        establishedTime: '',
        fax: '',
        fundsOut: '',
        contactPerson: '',
        imagine: '',
        importFee: '',
        industry: '',
        intermediateTitle: '',
        journalChinese: '',
        journalForeign: '',
        juniorTitle: '',
        master: '',
        supportCollege: '',
        phone: '',
        platformCategory: '',
        postgraduateNums: '',
        rdnums: '',
        reason: '',
        seniorTitle: '',
        significance: '',
        status: '',
        studyType: '',
        website: '',
        zipcode: ''
      },
      activeNames: ['1', '2', '3'],
      fileList: [],
      fileListLoading: false,
      platformAuditList: [],
      platformAuditListLoading: false,
      fileForm: {
        tplatformid: '',
        filedate: '',
        fileid: '',
        filename: '',
        filesize: '',
        flag: 0,
        fileurl: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'uid',
      'roles',
      'name',
      'dept'
    ]),
    MyPaperPost() {
      return {
        pageNum: this.p1_page,
        pageSize: this.p1_size,
        ...this.search
      }
    }
  },
  watch: {
    search: {
      handler() {
        this.paperListLoading = true
        clearTimeout(this.searchTimeout) // 清除之前的定时器
        this.searchTimeout = setTimeout(() => {
          this.fetchPaperData()
          this.paperListLoading = false
        }, 1500) // 设置新的定时器，1.5秒后执行查询
      },
      deep: true
    },
    status() {
      this.fetchPaperData()
    }
  },
  created() {
    this.fetchPaperData()
    this.fetchPlatformCategories()
  },
  methods: {
    querySearchAsync(queryString, cb) {
      getUserByAccount(queryString).then(response => {
        if (response.code === 200) {
          var results = []
          response.data.forEach(item => {
            const value = JSON.parse(
              JSON.stringify(item).replace(/account/g, 'value')
            )
            results.push(value)
          })
          clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            cb(results)
          }, 3000 * Math.random())
        }
      })
    },
    authorIdHandleSelect(item) {
      this.thesis_add_form2.contactPerson = item.name
      this.thesis_add_form2.contactPersonId = item.value
    },
    // 处理平台类别变化（兼容旧版本）
    handlePlatformCategoryChange(value) {
      // 根据传入的值判断是否是直接调用
      if (value === undefined) {
        // 如果没有传入值，则使用表单中的值
        console.log('平台类别已更改:', this.thesis_add_form2.platformCategory)
      } else {
        // 如果传入了值，则使用传入的值并更新搜索条件
        console.log('平台类别已更改:', value)
        this.search.platformCategory = value
        // 处理platformCategoryName
        if (value && value.length > 0 && this.nationalEconomy_options) {
          const result = this.findSelectedOptionWithPath(this.nationalEconomy_options, value)
          this.search.platformCategoryName = result?.path.join('/') || ''
        } else {
          this.search.platformCategoryName = ''
        }
      }
      // 如果需要，可以在这里添加其他逻辑
    },
    // 查找选中选项的路径
    findSelectedOptionWithPath(options, values, path = [], level = 0) {
      // 如果已经遍历完所有级联层级或没有更多选项
      if (level >= values.length || !options) return null
      const currentValue = values[level]
      for (const option of options) {
        const currentPath = [...path, option.label]
        if (option.value === currentValue) {
          // 如果是最后一级，返回找到的选项和路径
          if (level === values.length - 1) {
            return { option, path: currentPath }
          }
          // 否则继续查找下一级
          const found = this.findSelectedOptionWithPath(
            option.children,
            values,
            currentPath,
            level + 1
          )
          if (found) return found
        }
      }
      return null
    },
    // 处理编辑表单平台类别变化
    handleEditFormPlatformCategoryChange(value) {
      console.log('编辑表单平台类别已更改:', value)
      if (value && value.length > 0) {
        // 如果选择了值，则直接使用级联选择器的值数组
        this.thesis_add_form2.platformCategory = value
        console.log('设置编辑表单平台类别为:', this.thesis_add_form2.platformCategory)
        // 处理platformCategoryName
        if (this.nationalEconomy_options) {
          const result = this.findSelectedOptionWithPath(this.nationalEconomy_options, value)
          this.thesis_add_form2.platformCategoryName = result?.path.join('/') || ''
        }
      } else {
        // 如果清空了选择，则将平台类别也清空
        this.thesis_add_form2.platformCategory = []
        this.thesis_add_form2.platformCategoryName = ''
        console.log('清空编辑表单平台类别')
      }
      // 如果需要，可以在这里添加其他逻辑
    },

    // 获取学院列表数据
    fetchDeptData() {
      if (this.dept_options.length === 0) {
        this.deptLoading = true
        getDepts().then(response => {
          if (response.code === 200) {
            this.dept_options = response.data
            if (Object.keys(this.deptMap).length === 0) {
              this.deptMap = response.data.reduce((map, dept) => {
                map[dept.deptName] = dept.deptID
                return map
              }, {})
            }
            this.deptLoading = false
          }
        })
      }
    },
    // 获取平台类别列表
    fetchPlatformCategories() {
      // 返回Promise以便在其他方法中使用await或then
      return new Promise((resolve, reject) => {
        // 如果已经加载过数据，直接返回
        if (this.nationalEconomy_options && this.nationalEconomy_options.length > 0) {
          console.log('平台类别数据已加载，使用缓存数据')
          resolve(this.nationalEconomy_options)
          return
        }
        // 显示加载状态
        this.sourceCascaderLoading = true
        getPlatformCategories().then(response => {
          if (response.code === 200) {
            // 处理级联数据，提取所有类别名称
            const extractCategories = (items) => {
              let categories = []
              if (Array.isArray(items)) {
                items.forEach(item => {
                  if (item.label) {
                    categories.push({
                      value: item.label,
                      label: item.label
                    })
                  }
                  if (item.children && item.children.length > 0) {
                    categories = categories.concat(extractCategories(item.children))
                  }
                })
              }
              return categories
            }
            this.platformCategoryOptions = extractCategories(response.data)
            console.log('平台类别选项:', this.platformCategoryOptions)
            // 直接使用后端返回的完整三级数据
            this.nationalEconomy_options = response.data || []
            // 隐藏加载状态
            this.sourceCascaderLoading = false
            // 解析Promise
            resolve(this.nationalEconomy_options)
          } else {
            // 隐藏加载状态
            this.sourceCascaderLoading = false
            // 拒绝Promise
            reject(new Error('获取平台类别数据失败'))
          }
        }).catch(error => {
          // 隐藏加载状态
          this.sourceCascaderLoading = false
          // 拒绝Promise
          reject(error)
        })
      })
    },
    statusChange(val) {
      this.status = val
      this.search.status = val
    },
    statusFilter(status) {
      const statusMap = {
        '草稿': { type: 'info' },
        '待院审核': { type: 'warning' },
        '被院级退回': { type: 'danger' },
        '待校审核': { type: 'warning' },
        '被校级退回': { type: 'danger' },
        '审核通过': { type: 'success' }
      }
      return statusMap[status] || { type: 'info' }
    },
    // 以下为数据导出
    handleCheckAllChange(val) {
      this.check_fields = val ? this.fields_list : []
      this.isIndeterminate = false
      this.EXCEL.json_fields = JSON.parse(JSON.stringify(this.all_fields, this.check_fields))
    },
    handleCheckedFieldsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.fields_list.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.fields_list.length
      this.EXCEL.json_fields = JSON.parse(JSON.stringify(this.all_fields, this.check_fields))
    },
    async createExportData() {
      // 确保平台类别数据已加载
      if (!this.nationalEconomy_options || this.nationalEconomy_options.length === 0) {
        await this.fetchPlatformCategories()
      }
      return await getMyPaperList(this.MyPaperPost).then(response => {
        if (response.code === 200) {
          if (response.data.list.length === 0) {
            Message.warning('返回数据为空，导出失败！')
            this.loadingInstance.close()
          }
          // 处理导出数据，转换平台类别、录入人、录入日期等字段
          const processedData = response.data.list.map(item => {
            const processedItem = { ...item }
            // 处理平台类别：优先使用后端返回的platformCategoryName，否则转换platformCategory
            if (item.platformCategoryName) {
              // 如果后端已经返回了platformCategoryName，直接使用
              processedItem.platformCategoryName = item.platformCategoryName
            } else if (item.platformCategory && this.nationalEconomy_options) {
              // 如果platformCategory是数组，直接使用
              if (Array.isArray(item.platformCategory)) {
                const result = this.findSelectedOptionWithPath(this.nationalEconomy_options, item.platformCategory)
                processedItem.platformCategoryName = result?.path.join('/') || item.platformCategory.join('/')
              } else {
                // 如果是单个值，先查找路径再转换
                const categoryPath = this.findCategoryPath(item.platformCategory)
                if (categoryPath && categoryPath.length > 0) {
                  const result = this.findSelectedOptionWithPath(this.nationalEconomy_options, categoryPath)
                  processedItem.platformCategoryName = result?.path.join('/') || item.platformCategory
                } else {
                  // 如果找不到路径，直接查找单个值对应的标签
                  const directResult = this.findDirectCategoryLabel(item.platformCategory)
                  processedItem.platformCategoryName = directResult || item.platformCategory
                }
              }
            }
            // 处理项目负责人工号：确保字段存在
            if (item.contactPersonId) {
              processedItem.contactPersonId = item.contactPersonId
            }
            // 处理项目负责人：确保字段存在
            if (item.contactPerson) {
              processedItem.contactPerson = item.contactPerson
            }
            // 处理录入人：使用contactPerson字段
            if (item.contactPerson) {
              processedItem.Entered = item.contactPerson
            } else if (item.entered) {
              processedItem.Entered = item.entered
            }
            // 处理录入日期：确保格式正确
            if (item.enteredtime) {
              processedItem.EnteredTime = item.enteredtime
            }
            return processedItem
          })
          return processedData
        }
      })
    },
    startDownload() {
      this.excel_dialog = false
      this.loadingInstance = Loading.service({ text: '正在导出...' })
    },
    finishDownload() {
      setTimeout(() => {
        this.loadingInstance.close()
      }, 1000)
    },
    fetchPaperData() {
      this.paperListLoading = true
      getUserPlatforms(this.MyPaperPost).then(response => {
        if (response.code === 200) {
          this.paperList = response.data.list
          this.p1_total = response.data.total
          // 初始化committedButtons状态
          this.paperList.forEach(item => {
            // 根据状态判断是否已提交
            if (item.status === '待院审核' || item.status === '待校审核' || item.status === '审核通过' || item.status === '被院级退回' || item.status === '被校级退回') {
              this.committedButtons[item.id] = true
            } else {
              this.committedButtons[item.id] = false
            }
          })
          this.paperListLoading = false
        }
      })
    },
    p1_sizechange(newsize) {
      this.p1_size = newsize
      this.p1_page = 1
      this.fetchPaperData()
    },
    p1_currentchange(newpage) {
      this.p1_page = newpage
      this.fetchPaperData()
    },
    filterTag(value, row) {
      return row.operationStatus === value
    },
    thesis_back(row) {
      this.$prompt('请输入退回原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.+$/,
        inputErrorMessage: '原因不能为空'
      }).then(({ value }) => {
        this.back_post.id = row.id
        this.back_post.reason = value
        platform_back_xiaoji(this.back_post).then(response => {
          if (response.code === 200) {
            Message.success('退回成功')
            this.fetchPaperData()
          }
        })
      }).catch(() => {
        Message.info('取消退回')
      })
    },
    thesis_pass(index, row) {
      this.$refs[`popoverpass-${index}`].doClose()
      platform_pass_xiaoji(row.id).then(response => {
        if (response.code === 200) {
          Message.success('通过成功')
          this.fetchPaperData()
        }
      })
    },
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },

    addthesis() {
      this.thesis_add_dialog = true
      this.resetForm('thesis_add_form1')
      this.thesis_add_form1.enteredName = this.name
    },

    open_thesis_info_dialog(data) {
      this.thesis_info_dialog = true
      this.resetForm('thesis_add_form2')
      this.thesis_add_form2 = JSON.parse(JSON.stringify(data))

      // 确保已加载平台类别数据
      this.fetchPlatformCategories().then(() => {
        // 根据platformCategory查找对应的路径
        if (this.thesis_add_form2.platformCategory) {
          // 使用与 platform_view 一致的处理方式
          // 将字符串类型的platformCategory转换为数组
          const categoryPath = this.findCategoryPath(this.thesis_add_form2.platformCategory)
          if (categoryPath && categoryPath.length > 0) {
            this.thesis_add_form2.platformCategory = categoryPath
          }
        }
      })
    },

    // 查找类别路径
    findCategoryPath(categoryValue) {
      // 递归查找类别路径的辅助函数
      const findPath = (options, value, currentPath = []) => {
        for (const option of options) {
          // 创建当前路径的副本并添加当前选项的值
          const path = [...currentPath, option.value]

          // 如果找到匹配的值，返回路径
          if (option.value === value) {
            return path
          }

          // 如果有子选项，递归查找
          if (option.children && option.children.length > 0) {
            const result = findPath(option.children, value, path)
            if (result) {
              return result
            }
          }
        }

        // 如果没有找到匹配的值，返回null
        return null
      }

      // 在nationalEconomy_options中查找路径
      const path = findPath(this.nationalEconomy_options, categoryValue)

      // 如果找到路径，记录日志
      if (path) {
        console.log('找到平台类别路径:', path)
      } else {
        console.log('未找到平台类别路径:', categoryValue)
      }
      // 返回找到的路径，以便在其他函数中使用
      return path
    },

    // 直接查找单个类别值对应的标签
    findDirectCategoryLabel(categoryValue) {
      const findLabel = (options, value) => {
        for (const option of options) {
          if (option.value === value) {
            return option.label
          }
          if (option.children && option.children.length > 0) {
            const result = findLabel(option.children, value)
            if (result) {
              return result
            }
          }
        }
        return null
      }
      return findLabel(this.nationalEconomy_options, categoryValue) || categoryValue
    },
    // 处理依托学院选择变化
    handleSupportCollegeChange2(value) {
      if (value && this.deptMap[value]) {
        this.thesis_add_form2.supportCollegeid = this.deptMap[value]
        this.search.supportCollegeid = this.deptMap[value] // 同时更新搜索条件
      } else {
        this.thesis_add_form2.supportCollegeid = ''
        this.search.supportCollegeid = '' // 同时更新搜索条件
      }
    },
    save_add_form1(formdata) {
      formdata.entered = this.uid
      // 确保supportCollegeid字段被设置
      if (formdata.supportCollege && this.deptMap[formdata.supportCollege]) {
        formdata.supportCollegeid = this.deptMap[formdata.supportCollege]
      }
      console.log('提交给后端的数据 (save_add_form1):', formdata)
      console.log('supportCollegeid值:', formdata.supportCollegeid)
      platform_add(formdata).then(response => {
        if (response.code === 200) {
          Message.success('保存成功')
          this.thesis_add_dialog = false
          this.fetchPaperData()
        }
      })
    },
    save_add_form2(formdata) {
      // 确保supportCollegeid字段被设置
      if (formdata.supportCollege && this.deptMap[formdata.supportCollege]) {
        formdata.supportCollegeid = this.deptMap[formdata.supportCollege]
      }
      console.log('提交给后端的数据 (save_add_form2):', formdata)
      console.log('supportCollegeid值:', formdata.supportCollegeid)
      platform_update(formdata).then(response => {
        if (response.code === 200) {
          Message.success('保存成功')
          this.thesis_info_dialog = false
          this.fetchPaperData()
          this.infoview1 = formdata
        }
      })
    },
    delete_thesis(index, row) {
      this.$refs[`popoverdelete-${index}`].doClose()
      platform_delete(row.id).then(response => {
        if (response.code === 200) {
          Message.success('删除成功')
          this.fetchPaperData()
        }
      })
    },
    commit_thesis(index, row) {
      this.$refs[`popovercommit-${index}`].doClose()
      platform_commit(row.id, this.uid).then(response => {
        if (response.code === 200) {
          Message.success('提交成功')
          // 设置按钮状态为已提交
          this.committedButtons[row.id] = true
          this.fetchPaperData()
        }
      })
    },
    // 撤回科研平台
    withdraw_thesis(index, row) {
      this.$refs[`popoverwithdraw-${index}`].doClose()
      // 调用撤回API，模拟实现
      thesis_withdraw(row.id).then(response => {
        if (response.code === 200) {
          Message.success('撤回成功')
          // 设置按钮状态为未提交
          this.committedButtons[row.id] = false
          this.fetchPaperData()
        }
      })
    },
    open_infoview_dialog(row) {
      this.infoview_dialog = true
      this.infoview1 = JSON.parse(JSON.stringify(row))
      this.fetchPlatformAuditList()
      this.fileForm.tplatformid = row.id
      this.fetchFileData()
    },
    fetchPlatformAuditList() {
      if (this.infoview1.id) {
        this.platformAuditListLoading = true
        get_thesis_Audit(this.infoview1.id).then(response => {
          if (response.code === 200) {
            this.platformAuditList = response.data
          } else {
            this.platformAuditList = []
          }
          this.platformAuditListLoading = false
        }).catch(() => {
          this.platformAuditList = []
          this.platformAuditListLoading = false
        })
      }
    },
    // 以下是附件上传
    handleUploadClick() {
      if (this.infoview1.status === '待院审核' || this.infoview1.status === '待校审核' || this.infoview1.status === '审核通过') {
        this.$message.error('当前状态不可上传')
      }
    },
    beforeFileUpload(file) {
      if (this.infoview1.status === '待院审核' || this.infoview1.status === '待校审核' || this.infoview1.status === '审核通过') {
        this.$message.error('当前状态不可上传')
        return false
      }
      return true
    },
    handleFileSuccess(res, file, fileList) {
      this.fileForm.filename = file.name
      this.fileForm.filesize = file.size
      // 处理文件URL，确保正确存储相对路径
      let fileUrl = res.data
      if (fileUrl.startsWith(this.$FILE_PATH)) {
        // 去除 FILE_PATH 前缀，保留相对路径
        fileUrl = fileUrl.replace(this.$FILE_PATH, '')
      }
      // 确保路径以 / 开头
      if (!fileUrl.startsWith('/')) {
        fileUrl = '/' + fileUrl
      }
      this.fileForm.fileurl = fileUrl
      this.commit_file()
    },
    commit_file() {
      platform_add_file(this.fileForm).then(response => {
        if (response.code === 200) {
          Message.success('上传成功')
          this.fetchFileData()
        }
      })
    },
    fetchFileData() {
      this.fileListLoading = true
      platform_page_file(this.fileForm.tplatformid).then(response => {
        if (response.code === 200) {
          this.fileList = response.data
          this.fileListLoading = false
        }
      })
    },
    downloadFile(row) {
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      // 确保文件路径正确拼接，处理fileupload文件夹的路径
      let fileUrl = row.fileurl
      if (!fileUrl.startsWith('https')) {
        // 如果不是完整URL，则拼接FILE_PATH
        if (fileUrl.startsWith('/')) {
          fileUrl = this.$FILE_PATH + fileUrl
        } else {
          fileUrl = this.$FILE_PATH + '/' + fileUrl
        }
      }
      a.href = fileUrl
      a.target = '_blank'
      a.dispatchEvent(event)
    },
    deleteFile(index, row) {
      this.$refs[`popoverdelete-${index}`].doClose()
      platform_delete_file(row.fileid).then(response => {
        if (response.code === 200) {
          Message.success('删除成功')
          this.fetchFileData()
        }
      })
    }
  }
}
</script>

<style lang="scss">
.el-form{
  margin-left: 40px;
  .el-input,.el-select{
    width: 300px;
  }
}
.el-tag + .el-tag {
  margin: 10px 10px;
}
.margin-top {
  margin-top: 50px;
}
@media screen and (max-width:600px) {
  .el-dialog{
    width: 100% !important;
  }
  .el-form{
    margin-left: 25px;
  }
}
</style>
